package com.hue.nio.day02.one;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/*
    ServerSocketChannel编写服务端
 */
public class Test01 {
    public static void main(String[] args) throws Exception {
        //创建服务端
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //绑定端口
        serverSocketChannel.bind(new InetSocketAddress(7777));
        //创建选择器
        Selector selector = Selector.open();
        //将serverSocketChannel注册到selector上,监听连接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0) {
            //当有事件发生,获取所有key,轮询所有事件
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) { //是一个客户端连接
                    //获取连接的客户端通道
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //将客户端通道注册到selector上,监听读事件
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                } else if (key.isReadable()) {  //是读事件
                    //获取客户端通道
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    //读取数据
                    socketChannel.read(buffer);
                    buffer.flip();
                    System.out.println("客户端:" + new String(buffer.array(), 0, buffer.limit()));
                }
                //删除当前key
                iterator.remove();
            }
        }
    }
}
